package com.ecoolex.ying.space.core.manager;

import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.pojo.Page;
import com.ecoolex.framework.common.pojo.Pagination;
import com.ecoolex.framework.common.pojo.Sorting;
import com.ecoolex.framework.common.pojo.Sortings;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.ying.space.core.dao.MarktingWholeHouseCaseDAO;
import com.ecoolex.ying.space.entity.MarktingWholeHouseCase;
import com.ecoolex.ying.space.entity.MarktingWholeHouseCase.Column;
import com.ecoolex.ying.space.entity.MarktingWholeHouseCaseExample;
import com.ecoolex.ying.space.entity.MarktingWholeHouseCaseExample.Criteria;

import java.sql.Date;
import java.time.Instant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MarktingWholeHouseCaseManager {
	
    @Autowired
    private MarktingWholeHouseCaseDAO dao;
    
    public MarktingWholeHouseCase add(MarktingWholeHouseCase record, String createUser) {
    	BizAssert.isTrue(Check.notNullAndGtZero(record.getWeight()), ResultCode.VERIFY.build(10), "请输入大于0的有效权重");
    	record.setDeleted(MarktingWholeHouseCase.NOT_DELETED);
		record.setCreateUser(createUser);
		record.setCreateTime(Date.from(Instant.now()));
		record.setUpdateUser(createUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.insert(record);
		return record;
    }
    
    public void delete(MarktingWholeHouseCase record, String updateUser) {
    	record.setDeleted(MarktingWholeHouseCase.IS_DELETED);
    	record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(record, Column.deleted,Column.updateTime,Column.updateUser);
    }
    
    public MarktingWholeHouseCase getById(Integer id) {
    	return dao.selectByPrimaryKeyWithLogicalDelete(id, MarktingWholeHouseCase.NOT_DELETED);
    }
    
    public MarktingWholeHouseCase getMarktingWholeHouseCaseByCaseId(Integer caseId) {
    	MarktingWholeHouseCaseExample example = new MarktingWholeHouseCaseExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andCaseIdEqualTo(caseId).andDeletedEqualTo(MarktingWholeHouseCase.NOT_DELETED);
    	return dao.selectOneByExample(example);
    }
    
    public Pagination<MarktingWholeHouseCase> query(String name, Sorting[] sorts, Page page){
    	return Pagination.create(page, 
    			dao.count(name),
    			() -> dao.query(name, Sortings.builder(sorts).toSql(), page));
    }
    
    public MarktingWholeHouseCase getOnlineById(Integer id) {
    	return dao.getOnlineById(id);
    }
    
    public Pagination<MarktingWholeHouseCase> queryOnline(String name, Sorting[] sorts, Page page){
    	return Pagination.create(page, 
    			dao.countByOnline(name),
    			() -> dao.queryByOnline(name, Sortings.builder(sorts).toSql(), page));
    }
}